﻿using CinemaMaestro.WindowsApplication.EndPoints;
using MetroFramework;
using MetroFramework.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CinemaMaestro.WindowsApplication
{
    public partial class LoginForm : MetroForm
    {
        private HttpClient client;
        private AuthEndPoints endPoints;

        public LoginForm(HttpClient client)
        {
            this.client = client;
            endPoints = new AuthEndPoints(client);
            InitializeComponent();
            passwordTextBox.PasswordChar = '#';
        }

        private async void loginButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateCredentials())
                {
                    string token = await endPoints.GetAPIToken(emailTextBox.Text, passwordTextBox.Text);
                    if (token != String.Empty)
                    {
                        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                        
                        this.Hide();
                        MainForm form = new MainForm(client);
                        form.Closed += (s, args) => this.Close();
                        form.Show();
                    }
                    else
                    {
                        MetroMessageBox.Show(this, "Invalid credentials!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }   
            }
            catch
            {
                MetroMessageBox.Show(this, "Something went wrong! Cannot log you in!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand); 
            }         
        }

        private bool ValidateCredentials()
        {
            if (emailTextBox.Text == String.Empty)
            {
                MetroMessageBox.Show(this, "Please enter your an email address!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }
            if (passwordTextBox.Text == String.Empty)
            {
                MetroMessageBox.Show(this, "Please enter your password!", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }            
            return true;
        }

    }
}
